package com.example.nettydemo.decoder;

import com.example.nettydemo.dto.UserInfo;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class EchoClientHandler extends ChannelHandlerAdapter {

    private final String req = "abc$_";

    private int counter;

    public EchoClientHandler() {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        UserInfo[] infos = initUserInfo(1000);
        for(UserInfo userInfo : infos){
            // 每个都需要刷新? 粘包问题
            ctx.write(userInfo);
        }
        ctx.flush();
    }

    private UserInfo[] initUserInfo(int sendNumber) {
        UserInfo[] infos = new UserInfo[sendNumber];
        UserInfo userInfo = null;

        for(int i = 0; i < sendNumber; i++){
            userInfo = new UserInfo();
            userInfo.setAge(i);
            userInfo.setName("name_" + i);
            infos[i] = userInfo;
        }

        return infos;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.warn("客户端, 错误信息", cause);
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 为什么只接受到2个? 粘包问题
        log.info("response: [{}], counter: [{}]", msg, ++counter);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }


}
